<template>
  <el-dialog v-model="visible" width="900px" :title="!dataForm.id ? $t('add') : $t('update')"
    :close-on-click-modal="false" :close-on-press-escape="false">
    <el-form :model="dataForm" v-loading="loading" :rules="rules" ref="dataFormRef" @keyup.enter="dataFormSubmitHandle()"
      label-width="120px">

      <!-- <el-form-item label="年级" prop="gradeId" class="full">
        <el-select v-model="dataForm.gradeId" placeholder="选择年级">
          <el-option v-for="item in gradeList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item> -->
      <el-form-item label="分类" prop="subjectId" class="full">
        <el-select v-model="dataForm.subjectId" placeholder="选择分类">
          <el-option v-for="item in courseList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="类型" prop="type" class="full">
        <el-select v-model="dataForm.type" placeholder="选择类型">
          <el-option v-for="item in eduTypeList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item> -->

      <el-form-item prop="fileList" label="附件">
        <!-- <a :src="pdfUrl.filePath">{{ pdfUrl.fileName }}</a> -->
        <div class="wrapper">
          <el-upload class="avatar-uploader" :action="url + `/sys/oss/upload?token=${getToken()}`" :multiple="true" :show-file-list="true"
          :on-success="handleAvatarSuccess" :on-error="handleUploadError" :on-remove="handleRemove" :before-upload="beforeUploadHandle">
          <!-- <img v-if="imageUrl" :src="imageUrl" class="avatar" /> -->
          <el-icon class="avatar-uploader-icon">
            <Plus />
          </el-icon>
          <div class="list" v-for="(item, index) in multiFileList" :key="index">
            <span>{{ item.title }}</span>
          </div>
        </el-upload>
        </div>
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <el-button @click="visible = false">{{ $t("cancel") }}</el-button>
      <el-button type="primary" :disabled="!canSubmit" @click="dataFormSubmitHandle()">{{ btnText }}</el-button>
    </template>

  </el-dialog>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from "vue";
import baseService from "@/service/baseService";
import { useI18n } from "vue-i18n";
import { ElLoading, ElMessage } from "element-plus";
import { findObjectByPid, treeDataTranslate, validateMobile } from "@/utils/utils";
import { getToken } from "@/utils/cache";

const eduTypeList = ref([
  {
    label: "教案",
    value: 0,
  },
  {
    label: "试卷",
    value: 1,
  },
  {
    label: "课件",
    value: 2,
  },
  {
    label: "课件",
    value: 2,
  },
]);
const url = import.meta.env.VITE_APP_API;
const { t } = useI18n();
const emit = defineEmits(["refreshDataList"]);
const loading = ref(false)
const visible = ref(false);
const dataFormRef = ref();
const pdfLoading = ref();
const pdfUrl = ref<any>({
  fileName: '',
  filePath: '',
});
const rules = ref({
  gradeId: [{ required: true, message: t("validate.required"), trigger: ["blur", "change"] }],
  subjectId: [{ required: true, message: t("validate.required"), trigger: ["blur", "change"] }],
  type: [{ required: true, message: t("validate.required"), trigger: ["blur", "change"] }],
});

let dataForm = reactive({
  subjectId: "",
  gradeId: "",
  gradeName: "",
  subjectName: "",
  isHot: 0,
  isRecommend: 0,
  fileUrl: '',
  type: 0,
});
const courseList = ref();
const gradeList = ref();
const multiFileList = ref<any>([]); 
const uploadedCount = ref<any>(0);
const canSubmit = ref<any>(false);
const btnText = ref<any>('提交');
onMounted(() => {
  handleSubjectList();
  handleGradeList();
});

const handleSubjectList = async () => {
  try {
    const res = await baseService.get('/edu/subject/list')
    if (res.code == 0) {
      courseList.value = res.data;
    }
  } catch (error) {
    console.log('jj-error', error);

  }
}

const handleGradeList = async () => {
  try {
    const res = await baseService.get('/edu/grade/list')
    if (res.code == 0) {
      gradeList.value = res.data;
    }
  } catch (error) {
    console.log('jj-error', error);

  }
}

const init = (id?: any) => {
  visible.value = true;
};

const beforeUploadHandle = (file: any) => {
  btnText.value = '上传中';
  canSubmit.value = false;
  const fileName = file.name;
  const fileType = fileName.substring(fileName.lastIndexOf('.'));
  if(fileType !== '.pdf' && fileType !== '.mp4' && fileType !== '.mp3'){
    ElMessage.error({
      message: '请上传pdf,mp4,mp3格式的文件',
      duration: 500,
    });
      return false;
  }
// uploadFileName.value = "";
// pdfLoading.value = true;
};


const handleAvatarSuccess = (data: any, uploadFile: any, fileList: any) => {
  console.log('jj-fileList', fileList.length);
  uploadedCount.value = uploadedCount.value + 1;
  console.log('jj-uploadedCount.value', uploadedCount.value);
  if(uploadedCount.value  === fileList.length) {
    canSubmit.value = true;
    btnText.value = '提交';
  }
  // pdfLoading.value.close();
  if (data.code == 0) {
    const { fileName, filePath } = data?.data;
    multiFileList.value = [
      ...multiFileList.value,
      data?.data
    ]
  }
  ElMessage.success({
    message: "上传成功！",
    duration: 500,
  });
};

const handleRemove = (file: any, fileList: any) => {
  // 减去移除的文件数量
  // uploadedCount.value -= fileList.length - fileList.filter((f: any) => f).length;
};

const handleUploadError = () => {
  ElMessage.success({
    message: "上传失败！",
    duration: 500,
  });
}

// 表单提交
const dataFormSubmitHandle = () => {
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false;
    }
    const subjectName = courseList.value?.find((item: any) => item.id = dataForm?.subjectId)?.name;
    const gradeName = gradeList.value?.find((item: any) => item.id = dataForm?.gradeId)?.name;

    const parmas = {
      ...dataForm,
      subjectName,
      gradeName
    }
    const handleParams = multiFileList.value?.map((file: any) => {
      return {
        ...parmas,
        fileUrl: file.filePath,
        title: file.fileName,
      }
    })
    pdfLoading.value = ElLoading.service({
      lock: true,
      text: "正在上传",
      background: "rgba(0, 0, 0, 0.1)"
    });
    baseService.post('/edu/subject/file', handleParams).then((res) => {
      ElMessage.success({
        message: t("prompt.success"),
        duration: 500,
        onClose: () => {
          visible.value = false;
          emit("refreshDataList");
        }
      });
    }).finally(() => {
      pdfLoading.value.close();
    })
    // (!dataForm.id ? baseService.post : baseService.put)("/assess/user", {
    //   ...dataForm,
    //   freeTime: dataForm?.freeTime?.join(',')
    // }).then((res) => {
    //   ElMessage.success({
    //     message: t("prompt.success"),
    //     duration: 500,
    //     onClose: () => {
    //       visible.value = false;
    //       emit("refreshDataList");
    //     }
    //   });
    // });
  });
};

defineExpose({
  init
});
</script>
<style lang="less" scoped>
:deep(.el-dialog__body) {
  padding: 0 20px 20px 20px !important;
  max-height: calc(90vh - 116px);
}

:deep(.el-form-item) {
  width: calc(50% - 16px);

  &.full {
    width: 100%;

    &.address {
      display: flex;
    }
  }

  &.area-form-item {
    width: calc(33% - 16px);
  }
}

:deep(.el-upload-list) {
  width: 700px;
}

.wrapper {
  width: 100%;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}
</style>
